package com.longge.common.configuration;
import javax.annotation.Resource;

import org.jetbrains.annotations.NotNull;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestTemplate;

import com.longge.common.configuration.RestTemplateAutoConfiguration.RestConfig;
import com.longge.common.util.RestTemplateUtils;

import lombok.Getter;
import lombok.Setter;

/**
 * 工具类引导装配类
 * @author yangzhilong
 *
 */
@Configuration
@EnableConfigurationProperties(value = {RestConfig.class})
@ConditionalOnProperty(name = "rest.enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnClass(value = {HttpComponentsClientHttpRequestFactory.class})
public class RestTemplateAutoConfiguration {
    @Resource
    private RestConfig restConfig;
    
    /**
     * 使用Bootstrap来装配RestClient中的RestTemplate属性，
     * 避免直接装配RestTemplate来污染了正常的spring Cloud的调用
     * @return
     */
    @Bean
    public RestClientBootstrap bootstrap(){
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectTimeout(restConfig.getConnectTimeoutMs());
        httpRequestFactory.setReadTimeout(restConfig.getReadTimeoutMs());
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        RestTemplateUtils.setRestTemplate(restTemplate);
        return new RestClientBootstrap();
    }
    
    @Component
    @ConfigurationProperties(prefix = "rest")
    @Getter
    @Setter
    @Validated
    public static class RestConfig {
    	private Boolean enabled = Boolean.TRUE;
        @NotNull
        private Integer connectTimeoutMs = 3000;
        @NotNull
        private Integer readTimeoutMs = 6000;
    }
    
    /**
     * 空的引导类
     * @author yangzhilong
     *
     */
    static class RestClientBootstrap {
        
    }
}